const express = require("express");//得到一个express对象
const router = express.Router();
const db = require("../model/db");

//添加评论
router.post("/", async (req, res) => {
  const data = await db.Comment.create(
  req.body
  );
  res.send({
    code: 0,
    message: "",
    data
  });
})

//修改评论
router.put("/:id", async (req, res) => {
    await db.Comment.updateOne({
        _id: req.params.id
    }, req.body);

    res.send({
        "code": 0,
        "message": "修改成功",
        "data": true
    });

})

//删除评论
router.delete("/:id", async (req, res) => {
    await db.Comment.deleteOne({
        _id: req.params.id
    })
    res.send({
        "code": 0,
        "message": "删除成功",
        "data": true
    });
})

// 查询所有评论
router.get("/", async (req, res) => {
  if (!req.query.field) {//默认按照id排序
    req.query.field = "_id";

  }
  if (!req.query.sort) {//默认按照升序排序
    req.query.sort = "asc";
  }
  //拼接排序字符串
  let s = req.query.field;
  if (req.query.sort === "desc") {
    s = "-" + s;
  }

  //处理分页
  if (!req.query.page) {
    req.query.page == 1;//页索引默认为1
  }
  if (!req.query.limit) {
    req.query.limit == 10;//页容量 默认为10
  }
  const page = parseInt(req.query.page);
  const limit = parseInt(req.query.limit);

  let condition = {};
  if (req.query.key) {
    const exp = new RegExp(req.query.key, "i") //不区分大小写
    condition = {
      $or: [
        { commentator: {$regex: exp }},
        {content: {$regex: exp }},
        { order: {$regex: exp }},
        { character: {$regex: exp }},
        
      ]
    };
  }
  const data = await db.Comment.find(condition).sort(s).skip((page - 1) * limit).limit(limit);//升序降序 
  const count = await db.Comment.countDocuments(condition);
  res.send({
    code: 0,
    message: "",
    count,
    data
  });
})


module.exports = router;
